//
//  OnStageBlockManager.cpp
//  AvoidTheBlocks
//
//  Created by hoangtx on 6/19/13.
//
//

#include "OnStageBlockManager.h"
#include "StaticVariables.h"

bool OnStageBlockManager::init(){
    blockArray = CCArray::create();
    blockArray->retain();
    for(int i=0;i<NUMBER_OF_BLOCKS_ON_A_ROW;i++){
        CCArray* iArray = CCArray::create();
        blockArray->addObject(iArray);
    }
    
    

    return true;
}

void OnStageBlockManager::addTo(cocos2d::CCArray *arrayToAdd, Block *blockToAdd){
    CCArray* blockArrayOnColumn = (CCArray*)arrayToAdd->objectAtIndex(blockToAdd->getColumnIndex());
    blockArrayOnColumn->addObject(blockToAdd);
}

int OnStageBlockManager::getCountFromColumnThatHasTheLeastBlock(){
    int minCount = ((CCArray*)blockArray->objectAtIndex(0))->count();
    for(int i=1;i<NUMBER_OF_BLOCKS_ON_A_ROW;i++){
        int iCount = ((CCArray*)blockArray->objectAtIndex(i))->count();
        if(iCount < minCount){
            minCount = iCount;
        }
    }
    return minCount;
}

CCArray* OnStageBlockManager::getColumnArrayThatAreFull(){
    CCArray* resultArray = CCArray::create();
    for(int i=0;i<blockArray->count();i++){
        CCArray* iArray = (CCArray*)blockArray->objectAtIndex(i);
        if(iArray->count() >= NUMBER_OF_BLOCKS_ON_A_COLUMN){
            resultArray->addObject(CCInteger::create(i));
        }
    }
    return resultArray;
}

void OnStageBlockManager::checkForScoreARow(cocos2d::CCObject *sender){
    Block* droppedBlock = (Block*)sender;
    this->addTo(blockArray, droppedBlock);
    int minCount = getCountFromColumnThatHasTheLeastBlock();
    if(minCount == 0){
        return;
    }else{
        for(int i=0;i<blockArray->count();i++){
            CCArray* iArray = (CCArray*)blockArray->objectAtIndex(i);

            int minCountTemp = minCount;
            for(int j=0;j<minCountTemp;j++){
                Block* jBlock = (Block*)iArray->objectAtIndex(j);
                iArray->removeObject(jBlock);

                jBlock->minimize();
                j--;
                minCountTemp--;
            }
            
            
            for(int j=0;j<iArray->count();j++){
                Block* jBlock = (Block*)iArray->objectAtIndex(j);
                
                
                double distanceToDrop = jBlock->getBlockSize() * minCount;
                jBlock->dropByDistance(distanceToDrop);
                    
                
                
            }
        }
    }
}
